package com.health.healthproject.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.health.healthproject.common.Result;
import com.health.healthproject.dto.LoginRequest;
import com.health.healthproject.dto.LoginResponse;
import com.health.healthproject.entity.User;
import com.health.healthproject.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody @Valid LoginRequest loginRequest) {
        User user = userService.login(loginRequest.getUserPhone(), loginRequest.getPassword());
        if (user != null) {
            // 执行登录
            StpUtil.login(user.getId());
            // 获取登录信息
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();


            // 构建登录响应
            LoginResponse response = LoginResponse.builder()
                    .user(user)
                    .tokenName(tokenInfo.getTokenName())
                    .tokenValue(tokenInfo.getTokenValue())
                    .loginId(tokenInfo.getLoginId().toString())
                    .isLogin(tokenInfo.getIsLogin())
                    .build();

            return Result.success(response);
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getUserById(userId);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        StpUtil.logout();
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword")
    public Result<Void> updatePassword(@RequestParam Long id,
                                     @RequestParam String oldPassword,
                                     @RequestParam String newPassword) {
        // 校验登录状态和权限
        StpUtil.checkLogin();
        if (StpUtil.getLoginIdAsLong() != id) {
            return Result.error("无权修改他人密码");
        }

        String updateResult = userService.updatePassword(id, oldPassword, newPassword);
        if ("SUCCESS".equals(updateResult)) {
            // 密码修改成功后，清除用户的登录状态
            StpUtil.logout();
            return Result.success();
        }
        return Result.error(updateResult);
    }

    /**
     * 分页查询用户
     */
    @GetMapping("/page")
    public Result<Page<User>> queryUserPage(@RequestParam(defaultValue = "1") Integer current,
                                          @RequestParam(defaultValue = "10") Integer size,
                                          User user) {
        StpUtil.checkLogin();
        Page<User> page = userService.queryUserPage(new Page<>(current, size), user);
        return Result.success(page);
    }

    /**
     * 查询用户详情
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        StpUtil.checkLogin();
        User user = userService.getUserById(id);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        StpUtil.checkLogin();
        // 这里可以添加权限校验，例如只有管理员才能删除用户
        if (userService.deleteUser(id)) {
            return Result.success();
        }
        return Result.error("删除失败");
    }

    /**
     * 插入用户
     */
    @PostMapping("/insert")
    public Result<User> insertUser(@RequestBody User user) {
        //StpUtil.checkLogin();
        try {
            User insertedUser = userService.insertUser(user);
            return Result.success(insertedUser);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/getUserListByType")
    public Result<Page<User>> getUserListByType(@RequestParam(defaultValue = "1") Integer current,
                                                @RequestParam(defaultValue = "10") Integer size,
                                                @RequestParam(defaultValue = "1") int userType,
                                                @RequestParam(defaultValue = "") String userPhone) {
        Page<User> page = userService.getUserListByType(new Page<>(current, size), userType,userPhone);
        return Result.success(page);
    }

    @PutMapping("/update")
    public Result<User> updateUser(@RequestBody User user) {
        try {
            User updatedUser = userService.updateUser(user);
            if (updatedUser != null) {
                return Result.success(updatedUser);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}